﻿using AutoMapper;
using MediatR;
using Provenance.Domain.Slaughter;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Slaughter;
using Provenance.Read.Api.Application.Command.Slaughter;

namespace Provenance.Read.Api.Application.CommandHandler.Slaughter
{
    public class BackSlaughterInfoCommandHandler : IRequestHandler<BackSlaughterInfoCommand, ApiResult<SlaughterInfo>>
    {
        private readonly ISlaughterInfoRepository _slaughterInfoRepository;
        private readonly ILogger<BackSlaughterInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackSlaughterInfoCommandHandler(ISlaughterInfoRepository slaughterInfoRepository, ILogger<BackSlaughterInfoCommandHandler> logger, IMapper mapper)
        {
            _slaughterInfoRepository = slaughterInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<SlaughterInfo>> Handle(BackSlaughterInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _slaughterInfoRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                if (obj == null)
                {
                    return ApiResult<SlaughterInfo>.Failure("No slaughter info found for the given product info id");
                }
                return ApiResult<SlaughterInfo>.Success(obj);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting slaughter info for product info id {0}: {1}", request.ProductInfoId, ex.Message);
                return ApiResult<SlaughterInfo>.Failure(ex.Message);
            }
        }
    }
}
